package dal

import (
	"context"

	"lianzi_gos/internal/mods/mpweixin/schema"
	"lianzi_gos/pkg/errors"
	"lianzi_gos/pkg/util"

	"gorm.io/gorm"
)

// Get connection storage instance
func GetConnectionDB(ctx context.Context, defDB *gorm.DB) *gorm.DB {
	return util.GetDB(ctx, defDB).Model(new(schema.Connection))
}

// 联系我们
type Connection struct {
	DB *gorm.DB
}

// Query connections from the database based on the provided parameters and options.
func (a *Connection) Query(ctx context.Context, params schema.ConnectionQueryParam, opts ...schema.ConnectionQueryOptions) (*schema.ConnectionQueryResult, error) {
	var opt schema.ConnectionQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}

	db := GetConnectionDB(ctx, a.DB)
	if v := params.LikeName; len(v) > 0 {
		db = db.Where("username LIKE ?", "%"+v+"%")
	}
	if v := params.LikePhone; len(v) > 0 {
		db = db.Where("phone LIKE ?", "%"+v+"%")
	}
	if v := params.Status; len(v) > 0 {
		db = db.Where("status = ?", v)
	}

	var list schema.Connections
	pageResult, err := util.WrapPageQuery(ctx, db, params.PaginationParam, opt.QueryOptions, &list)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	queryResult := &schema.ConnectionQueryResult{
		PageResult: pageResult,
		Data:       list,
	}
	return queryResult, nil
}

// Get the specified connection from the database.
func (a *Connection) Get(ctx context.Context, id string, opts ...schema.ConnectionQueryOptions) (*schema.Connection, error) {
	var opt schema.ConnectionQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}

	item := new(schema.Connection)
	ok, err := util.FindOne(ctx, GetConnectionDB(ctx, a.DB).Where("id=?", id), opt.QueryOptions, item)
	if err != nil {
		return nil, errors.WithStack(err)
	} else if !ok {
		return nil, nil
	}
	return item, nil
}

// Exist checks if the specified connection exists in the database.
func (a *Connection) Exists(ctx context.Context, id string) (bool, error) {
	ok, err := util.Exists(ctx, GetConnectionDB(ctx, a.DB).Where("id=?", id))
	return ok, errors.WithStack(err)
}

// Create a new connection.
func (a *Connection) Create(ctx context.Context, item *schema.Connection) error {
	result := GetConnectionDB(ctx, a.DB).Create(item)
	return errors.WithStack(result.Error)
}

// Update the specified connection in the database.
func (a *Connection) Update(ctx context.Context, item *schema.Connection) error {
	result := GetConnectionDB(ctx, a.DB).Where("id=?", item.ID).Select("*").Omit("created_at").Updates(item)
	return errors.WithStack(result.Error)
}

// Delete the specified connection from the database.
func (a *Connection) Delete(ctx context.Context, id string) error {
	result := GetConnectionDB(ctx, a.DB).Where("id=?", id).Delete(new(schema.Connection))
	return errors.WithStack(result.Error)
}
